package controler;
import main.Test1;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.util.Vector;
import java.util.regex.Pattern;

import javax.imageio.ImageIO;

import model.ModelPlayer;
import modelImp.Player;
import view.*;

import ressources.Constant;

public class Preparing implements ActionListener 
{
	NewGameDialog ngd;
	ActifPlayersPanel actifPlayersPanel = new ActifPlayersPanel();
	
	
	public ActifPlayersPanel getActifPlayersPanel() {
		return actifPlayersPanel;
	}


	public Preparing(NewGameDialog ngd){
		this.ngd = ngd;
		
		this.ngd.getPlayButton().setActionCommand(Constant.key_newgame);
		this.ngd.getPlayButton().addActionListener(this);
		
		this.ngd.getCancelButton().setActionCommand(Constant.key_cancel);
		this.ngd.getCancelButton().addActionListener(this);
	}

	
	@Override
	public void actionPerformed(ActionEvent e) {
		/*
		 * New game: need 2 players minimum
		 */
		if(e.getActionCommand().equals(Constant.key_newgame)){
			String playersName[] = this.ngd.getNamesPlayer();
			Vector<ActifPlayerPanel> vectorActifPlayer = new Vector<ActifPlayerPanel>();
			Vector<String> playersValid = new Vector<String>();
			// Check name validity
			for(int i=0;i<playersName.length;i++){
				if(playersName[i]!=null && Pattern.matches("\\w++",playersName[i]))
				{
					playersValid.add(playersName[i]);
				}
			}
			
			
			// We can start the game
			if(playersValid.size() >=2){
				try{
					for(int i=0;i<playersValid.size();i++){
						InitGame.addPlayer(playersValid.get(i),ImageIO.read(new File (Constant.getPlayerImage(i))));
						vectorActifPlayer.add(new ActifPlayerPanel(Constant.getPlayerImage(i),(Player)InitGame.players.elementAt(InitGame.players.size()-1) ));
						
					}
					actifPlayersPanel = new ActifPlayersPanel(vectorActifPlayer);
					new Game(this.ngd.mainWindow.boardPanel,this.ngd.mainWindow.gamePanel);
					
				}catch(Exception exc){
					//TODO : message d'erreur
					InitGame.close();
				}
			}
			
					
			ngd.setVisible(false);
			ngd.setActifPlayersPanel(actifPlayersPanel);
		
		
		}
		
	}
}
